<template>
  <div class="selector" v-focus>
    <SelectorInput :placeholder="placeholder" :value="inputValue" @searchOptions="searchOptions" />
    <SelectorMenu :data="data" @setItemValue="setItemValue" :searchValue="searchValue" @updateSearch="updateSearch" :isReload="isReload" />
  </div>
</template>

<script>
import SelectorInput from "./Input"
import SelectorMenu from "./Menu"

export default {
  name: "YxSelector",
  data() {
    return {
      inputValue: "",
      searchValue: "",
    }
  },
  props: {
    data: Array,
    placeholder: String,
    isReload: {
      // 是否需要重新请求接口改变data的数据
      type: Boolean,
      default: false,
    },
  },
  directives: {
    focus: (el) => {
      const oSelectorInput = el.querySelector(".selector-input"),
        oSelectorMenu = el.querySelector(".selector-menu")

      const oInput = oSelectorInput.querySelector("input"),
        oIcon = oSelectorInput.querySelector("span")

      oInput.addEventListener(
        "focus",
        function () {
          oIcon.className = "iconfont icon-search"

          setTimeout(() => {
            oSelectorMenu.style.display = "block"
          }, 100)
        },
        false
      )

      oInput.addEventListener(
        "blur",
        function () {
          oIcon.className = "iconfont icon-arrow-down"
          setTimeout(() => {
            oSelectorMenu.style.display = "none"
          }, 100)
        },
        false
      )
    },
  },
  components: {
    SelectorInput,
    SelectorMenu,
  },
  methods: {
    setItemValue(item) {
      this.inputValue = item.label
      this.$emit("setItemValue", item.value)
    },

    searchOptions(value) {
      this.searchValue = value
    },

    updateSearch() {
      this.$emit("updateSearch")
    },
  },
}
</script>

<style lang="scss" scoped>
.selector {
  width: 100%;
  position: relative;
}
</style>
